<template>
  <el-button type="primary" v-per2="['userinfo-list','post']" @click="doAddUser">添加用户</el-button>
  <el-row style="margin-top:20px;">
    <el-form ref="searchFormRef" :inline="true" :model="state.searchForm">
      <el-form-item label="用户名" prop="username">
        <el-input style="width: 100px;" v-model="state.searchForm.username" placeholder="用户名" clearable/>
      </el-form-item>
      <el-form-item label="姓名" prop="nickname">
        <el-input style="width: 100px;" v-model="state.searchForm.nickname" placeholder="姓名" clearable/>
      </el-form-item>
      <el-form-item label="部门" prop="depart">
        <el-tree-select v-model="state.searchForm.depart" :data="state.searchForm.options.depart_list"
                        check-strictly
                        :render-after-expand="false"
                        show-checkbox
                        check-on-click-node
                        :props="{value:'id',label:'title'}"
                        node-key="id"
                        default-expand-all
                        highlight-current
                        filterable
                        clearable
                        style="width: 300px;"
                        placeholder="请选择"/>
      </el-form-item>
      <el-form-item label="登录时间" prop="date_range">
        <el-date-picker
            v-model="state.searchForm.date_range"
            type="daterange"
            start-placeholder="起始"
            end-placeholder="结束"
            :shortcuts="shortcuts"
            style="width: 200px;"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doSearch">搜 索</el-button>
        <el-button type="primary" @click="doResetSearchForm" plain>重 置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="state.tableData" border style="width: 100%" v-loading="state.isLoading"
              v-per2="['userinfo-list','get']">
      <el-table-column prop="username" label="用户名"/>
      <el-table-column prop="nickname" label="真实姓名"/>
      <el-table-column prop="depart_str" label="部门"/>
      <el-table-column prop="is_active" label="用户状态">
        <template #default="scope">
          <el-switch
              v-model="scope.row.is_active"
              inline-prompt
              active-text="是"
              inactive-text="否"
              :disabled="!hasPermission2('userinfo-active','patch')"
              @change="doActive(scope.row,scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="role_display" label="角色">
        <template #default="scope">
          <el-tag style="margin-right: 5px" type="primary" v-for="item in scope.row.role_display" :key="item.id">
            {{ item.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="last_login_time" label="登录时间"/>
      <el-table-column prop="last_login_ip" label="登录IP"/>
      <el-table-column v-per2="['userinfo-reset-password','put']" prop="is_super" label="重置密码">
        <template #default="scope">
          <el-button type="success" size="small" icon="Edit"
                     class="card-small-btn"
                     @click="doResetPwd(scope.row,scope.$index)">重置密码
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
          v-if="hasButton([{'name':'userinfo-detail','method':'delete'},{'name':'userinfo-detail','method':'put'}])"
          prop="username" label="操作">
        <template #default="scope">
          <el-popconfirm
              cancel-button-type="danger"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmUserDelete(scope.row)"
              title="确认删除吗?">
            <template #reference>
              <el-button v-per2="['userinfo-detail','delete']" type="danger" size="small" icon="Delete"
                         class="card-small-btn"></el-button>
            </template>
          </el-popconfirm>
          <el-button v-per2="['userinfo-detail','put']" type="success" size="small" icon="Edit" class="card-small-btn"
                     @click="doUserEdit(scope.row,scope.$index)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <MinePager v-per2="['userinfo-list','get']" :pager="state.pager"/>
  </el-row>
  <MineDialog :obj="state.userAddDialog"></MineDialog>
  <MineDialog :obj="state.userEditDialog"></MineDialog>
  <MineDialog :obj="state.resetPwdDialog"></MineDialog>
</template>

<script setup>

import {onMounted, reactive, ref} from "vue";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus";
import MineDialog from "@/components/DialogDouble.vue";
import MinePager from "@/components/MinePager.vue";
import {clearFormError, validateFormError} from "@/plugin/form.js";
import {hasButton, hasPermission2} from "@/stores/permission.js";

const searchFormRef = ref(null)
const shortcuts = [
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date()
      end.setTime(end.getTime() + 3600 * 1000 * 24)
      return [start, end]
    },
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
const state = reactive({
  isLoading: false,
  tableData: [],
  pager: {
    currentPage: 1,
    totalCount: 0,
    perPageSize: Number(localStorage.getItem("pageSize")) || 10,
    handleSizeChange: handleSizeChange,
    handleChangePage: handleChangePage
  },
  editId: -1,
  editIndex: -1,
  is_active: 1,
  userAddDialog: {
    visible: false,
    title: "添加用户",
    data: [],
    form: {
      username: "",
      nickname: "",
      password: "",
      confirm_password: "",
      roles: [],
      depart: ""
    },
    rules: {
      username: [
        {required: true, message: '用户名不能为空', trigger: 'blur'}
      ],
      nickname: [
        {required: true, message: '姓名不能为空', trigger: 'blur'}
      ],
      depart: [
        {required: true, message: '单位不能为空', trigger: 'blur'}
      ]
    },
    errors: {
      username: "",
      nickname: "",
      password: "",
      confirm_password: "",
      roles: "",
      depart: ""
    },
    fields: [
      {name: 'username', label: '用户名', wiget: 'input'},
      {name: 'nickname', label: '真实姓名', wiget: 'input'},
      {name: 'password', label: '密码', wiget: 'password'},
      {name: 'confirm_password', label: '确认密码', wiget: 'password'},
      {name: 'depart', label: '单位', wiget: 'tree_select'},
      {name: 'roles', label: '角色', wiget: 'checkbox'},
    ],
    options: {
      roles: []
    },
    doSubmit: doUserSubmit
  },

  userEditDialog: {
    visible: false,
    title: "编辑用户",
    data: [],
    form: {
      username: "",
      nickname: "",
      depart: "",
      roles: []
    },
    errors: {
      username: "",
      nickname: "",
      is_super: "",
      depart: "",
      roles: ""
    },

    fields: [
      {name: 'username', label: '用户名', wiget: 'input'},
      {name: 'nickname', label: '真实姓名', wiget: 'input'},
      {name: 'roles', label: '角色', wiget: 'checkbox'},
      {name: 'depart', label: '单位', wiget: 'tree_select'},
    ],
    options: {
      roles: [],
    },
    doSubmit: doUserSubmit
  },

  resetPwdDialog: {
    visible: false,
    title: "重置密码",
    form: {
      password: "",
      confirm_password: ""
    },
    errors: {
      password: "",
      confirm_password: ""
    },
    fields: [
      {name: 'password', label: '密码', wiget: 'password'},
      {name: 'confirm_password', label: '确认密码', wiget: 'password'},

    ],
    doSubmit: doResetPwdSubmit
  },

  searchForm: {
    username: "",
    depart: "",
    date_range: "",
    nickname: "",
    options: {
      depart_list: []
    }

  }
})

onMounted(() => {
  initTableData()
  initDepart()
  initRole()
})

function initDepart() {
  _axios.get('/api/web/user/depart/').then((res) => {
    if (res.data.code === 0) {
      state.userAddDialog.data = res.data.data
      state.userEditDialog.data = res.data.data
      state.searchForm.options.depart_list = res.data.data
    }
  })
}

function initRole() {
  _axios.get('/api/web/user/role/').then((res) => {
    if (res.data.code === 0) {
      state.userAddDialog.options.roles = res.data.data
      state.userEditDialog.options.roles = res.data.data
    }
  })
}

function initTableData() {
  if (!hasPermission2("userinfo-list", "get")) {
    return
  }
  state.isLoading = true
  let search_params = {page: state.pager.currentPage, page_size: state.pager.perPageSize}
  for (let key in state.searchForm) {
    let value = state.searchForm[key]
    if (key === "options") {
      continue
    }
    if (!value) {
      continue
    }
    if (key === "date_range") {
      search_params["start_date"] = value[0]
      search_params["end_date"] = value[1]
    } else {
      search_params[key] = value
    }
  }
  _axios.get("/api/web/user/", {params: search_params}).then((res) => {
    if (res.data.code === 0) {
      state.tableData = res.data.data.data;
      state.pager.totalCount = res.data.data.totalCount;
      state.pager.perPageSize = res.data.data.perPageSize
      state.isLoading = false
    }
  })
}

function doSearch() {
  state.pager.currentPage = 1
  initTableData()
}

function handleChangePage(page) {
  state.pager.currentPage = page
  initTableData()
}

function handleSizeChange(page_size) {
  localStorage.setItem("pageSize", page_size)
  state.pager.perPageSize = page_size
  state.pager.currentPage = 1
  initTableData()
}

function doAddUser() {
  state.userAddDialog.visible = true
  state.editId = -1
  state.editIndex = -1
  clearFormError(state.userAddDialog.errors)
  state.userAddDialog.form = {
    username: "",
    nickname: "",
    password: "",
    confirm_password: "",
    is_super: false,
    depart: "",
    roles: []
  }
}

function confirmUserDelete(row) {
  _axios.delete(`/api/web/user/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      state.tableData = state.tableData.filter((item) => {
        return row.id !== item.id
      })
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  })
}

function doUserEdit(row, index) {
  clearFormError(state.userEditDialog.errors)
  state.userEditDialog.visible = true
  state.userEditDialog.title = '编辑用户'
  state.editId = row.id
  state.editIndex = index
  let userDict = state.tableData[index]
  state.userEditDialog.form = {
    username: userDict.username,
    nickname: userDict.nickname,
    is_super: userDict.is_super,
    roles: userDict.roles,
    depart: userDict.depart
  }

}

function doUserSubmit() {
  if (state.editId > 0) {
    _axios.put(`/api/web/user/${state.editId}/`, state.userEditDialog.form).then((res) => {
      if (res.data.code === 0) {
        state.tableData[state.editIndex] = res.data.data
        state.editId = -1
        state.editIndex = -1
        state.userEditDialog.visible = false
      } else if (res.data.code === 2001) {
        validateFormError(state.userEditDialog.errors, res.data.detail)
      } else {
        ElMessage.error("编辑失败")
      }
    })
  } else {
    _axios.post('/api/web/user/', state.userAddDialog.form).then((res) => {
      if (res.data.code === 0) {
        state.userAddDialog.visible = false
        initTableData()
      } else if (res.data.code === 2001) {
        validateFormError(state.userAddDialog.errors, res.data.detail)
      } else {
        ElMessage.error("添加失败")
      }
    })
  }
}

function doResetPwd(row, index) {
  state.resetPwdDialog.visible = true
  clearFormError(state.resetPwdDialog.errors)
  state.resetPwdDialog.form = {
    password: "",
    confirmPassword: ""
  }
  state.editId = row.id
  state.editIndex = index
}

function doResetPwdSubmit() {
  clearFormError(state.resetPwdDialog.errors)
  _axios.put(`/api/web/user/${state.editId}/reset_password/`, state.resetPwdDialog.form).then((res) => {
    if (res.data.code === 0) {
      state.resetPwdDialog.visible = false
    } else if (res.data.code === 2001) {
      validateFormError(state.resetPwdDialog.errors, res.data.detail)
      // for (let key in res.data.detail) {
      //   state.resetPwdDialog.errors[key] = res.data.detail[key][0]
      // }
    } else {
      ElMessage.error("密码重置失败")
    }
  })
}

function doResetSearchForm() {
  searchFormRef.value.resetFields()
}

function doActive(row, index) {
  _axios.patch(`/api/web/user/${row.id}/active/`, {is_active: state.tableData[index].is_active}).then((res) => {
    if (res.data.code === 0) {
      ElMessage.success("用户状态修改成功")
    } else {
      ElMessage.error("用户状态修改失败")
    }
  })
}
</script>

<style scoped>

</style>